<template>
  <div class="app-container">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="所属公司">
        <el-select v-model="formInline.gongsiSel" @change="initData" placeholder="所属公司">
          <el-option v-for="val in gongsiList" :key="val.id" :label="val.name" :value="val.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="check">查询</el-button>
      </el-form-item> -->
    </el-form>
    <el-button type="primary" @click="handleAddRole">
      新增
    </el-button>

    <el-table :data="dataList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" prop="name" label="营销模板名称">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="设备模板">
        <template slot-scope="scope">
          {{ scope.row.deviceTemplateName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          {{ timeChange(scope.row.created) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'修改模板':'新增模板'" width="1100px">
      <el-form :model="role" :rules="rules" ref="ruleForm" label-width="160px" label-position="left">
        <el-form-item label="所属公司" prop="tenantId">
          <el-select v-model="role.tenantId" @change="tenantExchange" placeholder="所属公司">
            <el-option v-for="val in gongsiList" :key="val.id" :label="val.name" :value="val.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="营销模板名称" prop="name">
          <el-input v-model="role.name" placeholder="营销模板名称" />
        </el-form-item>
        <el-form-item label="选择设备模板" prop="deviceTemplateId">
          <el-select v-model="deviceTemplateId" :disabled="dialogType==='edit'" @change="getTemplateSel" placeholder="设备模板">
            <el-option v-for="(val,index) in mobanList" :key="index" :label="val.name" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择商品" >
          <div v-if="deviceTemplateId!=='' || dialogType==='edit'">
            <div v-for="(val,index) in marketingTemplateRules" :key="index" style="margin-bottom: 20px;">
              <span style='margin-right: 10px;'>{{val}}: </span>
              <el-select v-model="role.skus[index].id" @change="proEx(index)" filterable placeholder="选择商品">
                <el-option v-for="val in productList" :key="val.id" :label="val.name" :value="val.id"></el-option>
              </el-select>    
              <div style="display:inline-block;margin-left:10px;">
                商品总量
                <el-input style="display:inline-block;width:100px;margin-left: 20px;" type="number" v-model="role.skus[index].max" placeholder="库存总量" />
              </div>     
              <div style="display:inline-block;margin-left:10px;">
                商品单价
                <el-input style="display:inline-block;width:100px;margin-left: 20px;" type="number" v-model="role.skus[index].price" placeholder="库存总量" />
              </div>   
              <div style="display:inline-block;margin-left:10px;">
                商品折扣
                <el-input style="display:inline-block;width:100px;margin-left: 20px;" type="number" v-model="role.skus[index].discount" placeholder="库存总量" />
              </div>    
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">
          取消
        </el-button>
        <el-button type="primary" @click="confirm('ruleForm')">
          确定
        </el-button>
      </div>
    </el-dialog>
    <!-- <Pagination :total="total" :page="page+1" @pagination="pagination" /> -->
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import { getMarketingTenant, getMarketingTemplate, postMarketingTemplate, deleteMarketingTemplate, putMarketingTemplate } from '@/api/MarketingTemplate'
import { listTenant } from '@/api/TenantGoods'
import { getDeviceTemplate } from '@/api/DeviceTemplate'
import Pagination from '@/components/Pagination/index'

const defaultRole = {
  id: '',
  name: '',
  deviceTemplateId:'',
  skus:[],
  tenantId:''
}

export default {
  data() {
    return {
      role: Object.assign({}, defaultRole),
      dataList: [],
      dialogVisible: false,
      dialogType: 'new',
      rules: {
        name: [
          { required: true, message: '请输入营销模板名称' },
        ],
        deviceTemplateId: [
          { required: true, message: '请选择设备模板' },
        ],
        tenantId: [
          { required: true, message: '请选择所属公司' },
        ],
      },
      mobanList:[],
      productList:[],
      gongsiList:[],
      total: 20,
      page: 1,
      formInline: {
        name: '',
        gongsiSel: ''
      },
      marketingTemplateRules:[],
      deviceTemplateId:'',
      obj:{}
    }
  },
  computed: {
  },
  components: { Pagination },
  created() {
    this.gongsiList = JSON.parse(localStorage.getItem('companyList'));
    this.formInline.gongsiSel = this.gongsiList[0].id;
    this.initData();
    this.getDeviceTemplate_list();
  },
  methods: {
    //列表
    initData(){
      getMarketingTenant(this.formInline.gongsiSel).then((res)=>{
        this.dataList = res.result;
      })
    },
    //时间格式转化
    timeChange(UTCDateString) {
      if (!UTCDateString) {
        return '-';
      }
      function formatFunc(str) {
        return str > 9 ? str : '0' + str
      }
      var date2 = new Date(UTCDateString);
      console.log('时间', date2)
      var year = date2.getFullYear();
      var mon = formatFunc(date2.getMonth() + 1);
      var day = formatFunc(date2.getDate());
      var hour = date2.getHours();
      var noon = hour >= 12 ? 'PM' : 'AM'; // 判断是上午还是下午
      hour = hour >= 12 ? hour - 12 : hour; // 12小时制
      hour = formatFunc(hour);
      var min = formatFunc(date2.getMinutes());
      var sec = formatFunc(date2.getSeconds());
      var dateStr = year + '-' + mon + '-' + day + ' ' + hour + ':' + min + ':' + sec;
      return dateStr;
    },
    //公司商品库
    goodData(){
      var data = {
        searchCriteria: {
          name: '',
          barCode: "",
          type: 0,
        },
        pageCount: 10000,
        page: 0
      };
      listTenant(this.role.tenantId,data).then((res)=>{
        console.log(res)
        this.productList = res.result.goods;
      })
    },
    proEx(index){
      console.log(this.role.skus)
      console.log(index)
    },
    //新增变更所属公司
    tenantExchange(data){
      this.goodData();
      // this.getDeviceTemplate_list();
    },
    getDeviceTemplate_list(){
      getDeviceTemplate(this.role.tenantId).then((res)=>{
        this.mobanList = res.result;
      })
    },
    getTemplateSel(index){
      this.role.skus=[];
      this.role.deviceTemplateId = this.mobanList[index].id;
      this.marketingTemplateRules = this.mobanList[index].marketingTemplateRules;
      // this.role.deviceTemplateId = index.id;
      // this.marketingTemplateRules = index.marketingTemplateRules;
      var list = {
        id: "",
        name: "",
        max: 0,
        current: 0,
        locIndex: "",
        weight: 0,
        skuId: "",
        barCode: "",
        price: 0,
        skuImageUri: ""
      };
      for(let i=0;i<this.marketingTemplateRules.length;i++){
        this.role.skus.push(JSON.parse(JSON.stringify(list)));
        this.role.skus[i].locIndex = this.marketingTemplateRules[i]
      }
      console.log(this.marketingTemplateRules)
    },
    //过滤查询
    check(){
      this.initData();
    },
    //分页
    pagination(data) {
      this.page = data-1;
      this.initData();
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole)
      this.deviceTemplateId = '';
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      console.log(scope)
      this.marketingTemplateRules =[];
      getMarketingTemplate(scope.row.id).then((res)=>{
        for(let i=0;i<res.result.skus.length;i++){
          this.marketingTemplateRules.push(res.result.skus[i].locIndex)
        }
        for(let k=0;k<this.mobanList.length;k++){
          if(scope.row.deviceTemplateName === this.mobanList[k].name){
            this.deviceTemplateId = k;
          }
        }
        console.log(this.deviceTemplateId)
        this.dialogType = 'edit'
        this.dialogVisible = true
        this.role = deepClone(res.result)
        this.goodData();
        // this.getDeviceTemplate_list();
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确认删除?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          deleteMarketingTemplate(row.id).then((res)=>{
            this.initData();
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        })
        .catch(err => { console.error(err) })
    },
    async confirm(formName) {
      if(this.dialogType == 'edit'){
        putMarketingTemplate(this.mobanList[this.deviceTemplateId].id,{name: this.role.name,tenantId:this.role.tenantId,deviceTemplateId: this.mobanList[this.deviceTemplateId].id,skus:this.role.skus}).then((res)=>{
          this.dialogVisible = false;
          this.initData();
          this.$message({
            type: 'success',
            message: '编辑成功!'
          })
        })
      }else{
        console.log(this.role)
        this.$refs[formName].validate((valid) => {
          if (valid) {            
            for(let i=0;i<this.role.skus.length;i++){
              this.role.skus[i].max = Number(this.role.skus[i].max);
              this.role.skus[i].price = Number(this.role.skus[i].price);
              this.role.skus[i].discount = Number(this.role.skus[i].discount);
              this.role.skus[i].skuid = this.role.skus[i].id;
              if(!this.role.skus[i].id){
                delete this.role.skus[i].id;
              }
            }
            postMarketingTemplate({name: this.role.name,tenantId:this.role.tenantId,deviceTemplateId: this.role.deviceTemplateId,skus:this.role.skus}).then((res)=>{
              this.dialogVisible = false
              this.initData();
              this.$message({
                type: 'success',
                message: '创建成功!'
              })
            })
          }else{
            return
          }
        })
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
